/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

//El Objeto imagen contiene la fuente de la imagen, un histograma para cada canal y la imagen (opcional)

package gizmo;

import dao.GizmoJpaController;
import dao.exceptions.PreexistingEntityException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import processing.core.PApplet;
import processing.core.PImage;
import vo.Gizmo;

/**
 *
 * @author Steven
 */
public class Image extends PApplet{

public String src;
public String colors;
public PImage img;
public int[] dfred = new int [256];
public int[] dfgreen = new int [256];
public int[] dfblue = new int [256];

public Image(String image){

        this.src=image;
	this.img=loadImage(this.src);
        this.img.resize(500, 500);
        BuildHist();
        String x="";
        x+=(toString(this.dfred)+";");
        x+=(toString(this.dfgreen)+";");
        x+=(toString(this.dfblue)+";");
        this.colors=x;
        //System.out.println(this.colors);
        this.save();
        
}
public Image(PImage image){

	this.img=image;
        this.img.resize(500, 500);
        BuildHist();
        String x="";
        x+=(toString(this.dfred)+";");
        x+=(toString(this.dfgreen)+";");
        x+=(toString(this.dfblue)+";");
        this.colors=x;

}


public void save(){
    GizmoJpaController control = new GizmoJpaController();
    Gizmo insert = new Gizmo(this.src, this.colors);
        try {control.create(insert);}
        catch (PreexistingEntityException ex) {Logger.getLogger(Image.class.getName()).log(Level.SEVERE, null, ex);}
        catch (Exception ex) {Logger.getLogger(Image.class.getName()).log(Level.SEVERE, null, ex);}
}

//Buscar imagenes haciendo el contraste con todas las imagenes de la base de datos
//y comparandolas por medio de un histograma
public PImage searchByColor(){
    PImage p;
    String aux;
    GizmoJpaController Gjpa = new GizmoJpaController();
    List<Gizmo> myResults=Gjpa.findGizmoEntities();

    List<String>myImages=new ArrayList<String>();

    String[] red=((toString(this.dfred).split("-"))),
            green=((toString(this.dfgreen).split("-"))),
            blue=((toString(this.dfblue).split("-")));

    Gizmo temp=new Gizmo();
    String[] r,g,b;

    for(int i=0; i<myResults.size();i++){
        temp=myResults.get(i);

        r=((temp.getColors().split(";"))[0].split("-"));
        g=((temp.getColors().split(";"))[1].split("-"));
        b=(temp.getColors().split(";"))[2].split("-");

        if(near(r,red) && near(g,green) && near(b,blue)){
            //aux=myResults.get(random(myResults.size())).getSrc();
            aux=temp.getSrc();
            //System.out.print(":)");
            myImages.add(aux);
        }
    }

    if(myImages.size()>0){
        try{
            do{
            p=loadImage(myImages.get(random(myImages.size())));
            }while(p==null);
            }catch(Exception e){p=this.img;}
    System.out.println(":D");}
    else{p=this.img;System.out.println(":(");}
    return p;
}

//Construccion de los histogramas rojo, azl, y verde, para una imagen
public void BuildHist(){

    int myred;
    int myblue;
    int mygreen;

    int[]redh=new int[256];
    int[]greenh=new int[256];
    int[]blueh=new int[256];

    for(int i=0;i<this.img.pixels.length;i++){
        int auxrgb=this.img.pixels[i];

        myred=(auxrgb>> 16 & 0xFF);
        redh[myred]=redh[myred]+1;

        mygreen=(auxrgb>> 8 & 0xFF);
        greenh[mygreen]=greenh[mygreen]+1;
        
        myblue=(auxrgb & 0xFF);
        blueh[myblue]=blueh[myblue]+1;
        }

    this.dfred=redh;
    this.dfgreen=greenh;
    this.dfblue=blueh;

}
public String toString(int[]X){
    String result="";
    for(int i=0;i<X.length;i++){
        result+=X[i]+"-";
    }
    return result;
}

public String toString(String[]X){
    String result="";
    for(int i=0;i<X.length;i++){
        result+=X[i]+"-";
    }
    return result;
}

public static int random(int limit){
    limit = limit-1;
    int x =(int)(Math.random()*(limit));
    return x;
}

//Determina si una imagen, por medio de los histogramas, es cercana en color a otra
public boolean near(String[] x, String[] y){

    double boo=0;
    double aux=0;

    double aux1, aux2;
    
    for(int i=0; i<256;i++){
        aux1=Double.parseDouble(x[i]);
        aux2=Double.parseDouble(y[i]);
        aux=Math.pow((aux1-aux2),2);
        boo=boo+aux;
    }
    boo=Math.sqrt(boo);

    if(boo<70000){
       return true;}
    else {return false;}
}

}
